﻿using Engine;
using Game.Server.Event;
using Game.Server.PlayerEvent;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System;
using Game.NetWork.Packages;
using Game.NetWork;
using System.Text;
using System.Security.Cryptography;

namespace Game.Server.Plugins
{
    public class MajorCityArea
    {
        public Point3 MinPoint;
        public Point3 MaxPoint;
    }

    public class MajorCityZHPlugin : ServerPlugin, IPlayerBreakAndPlaceHandle, IExplodeEventHandle, IFireEventHandle, IPlayerInteractEventHandle, IMessageEventHandle
    {
        public override int Version => 10000;

        public override string Name => "主城防破坏插件";

        public byte FirstLevel => 0;

        private static string ConfigFilePath => Storage.GetSystemPath(ServerManager.PluginsPath + "/MajorCityAreas.json");

        public SubsystemGameInfo SubsystemGameInfo;


        /// <summary>
        /// 主城范围
        /// </summary>
        public static List<MajorCityArea> MajorCityAreas = new List<MajorCityArea>(); 

        /// <summary>
        /// 是否在主城范围内
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public bool IsInMajorCityAreas(Point3 point)
        {
            if(SubsystemGameInfo != null)
            {
                foreach (var area in MajorCityAreas)
                {
                    if (area.MinPoint.X <= point.X && area.MinPoint.Y <= point.Y && area.MinPoint.Z <= point.Z && area.MaxPoint.X >= point.X && area.MaxPoint.Y >= point.Y && area.MaxPoint.Z >= point.Z)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public override void Initialize()
        {
            PlayerBreakAndPlaceBlockEventManager.AddObject(this);
            ExplodeEventManager.AddObject(this);
            FireEventManager.AddObject(this);
            PlayerInteractEventManager.AddObject(this);
            MessageEventManager.AddObject(this);
        }

        public bool PlayerBreakEvent(ComponentPlayer componentPlayer, Point3 point, int digBlockValue, int toolLevel)
        {
            if (!componentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(point))
            {
                DisplaySmallMessageNet(componentPlayer, "不可在主城破坏方块！");
                return false;
            }
            return true;
        }

        public bool PlayerPlaceEvent(ComponentPlayer componentPlayer, Point3 point, int placeBlockValue)
        {
            if (!componentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(point))
            {
                DisplaySmallMessageNet(componentPlayer, "不可在主城放置方块！");
                return false;
            }
            return true;
        }
        
        public void Explode(int x, int y, int z, ref float pressure, bool isIncendiary, bool noExplosionSound, PlayerData miner)
        {
            if (IsInMajorCityAreas(new Point3(x, y, z)))
            {
                pressure = 0;
            }
        }
      
        public bool Fire(Ray3 ray, ComponentMiner componentMiner)
        {
            return true;
        }

        public bool FireTerrain(CellFace cellFace, ComponentMiner componentMiner)
        {
            if (!componentMiner.ComponentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(cellFace.Point))
            {
                DisplaySmallMessageNet(componentMiner.ComponentPlayer, "不可在主城放火！已记录备案！");
                var client = componentMiner.ComponentPlayer.PlayerData.Client;
                Log.Information($"玩家:{client.Nickname} 社区ID:{client.CommunityAccountId}  尝试在主城放火");
                return false;
            }
            return true;
        }

        public void ReceiveMessage(string playerName, NetNode netNode, Client From, string message, byte messageType, out bool External)
        {
            External = false;
        }

        public bool EditSignMessage(Point3 point, ComponentPlayer componentPlayer)
        {
            if (!componentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(point))
            {
                return false;
            }
            return true;
        }


        public bool Interact(ComponentPlayer componentPlayer, CellFace cellFace)
        {
            return true;
        }

        public bool Use(ComponentPlayer componentPlayer, object raycast, int activeBlockValue)
        {
            if(Terrain.ExtractContents(activeBlockValue) == 230 && raycast is TerrainRaycastResult)
            {
                Point3 point = ((TerrainRaycastResult)raycast).CellFace.Point;
                if (!componentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(point))
                {
                    DisplaySmallMessageNet(componentPlayer, "不可在主城使用锤子！已记录备案");
                    var client = componentPlayer.PlayerData.Client;
                    Log.Information($"玩家:{client.Nickname} 社区ID:{client.CommunityAccountId} 尝试在主城({point.ToString()})使用锤子");
                    CommonLib.Net.RemoveClient(client, "不可在主城使用锤子！已记录备案"); 
                    return false;
                }
            }
            return true;
        }

        public bool Hit(ComponentPlayer componentPlayer, ComponentBody componentBody, Vector3 hitPoint, Vector3 hitDirection)
        {
            return true;
        }

        public bool Aim(ComponentPlayer componentPlayer, int activeBlockValue, Ray3 aim, AimState state)
        {
            if (!componentPlayer.PlayerData.ServerManager && IsInMajorCityAreas(new Point3(aim.Position)))
            {
                DisplaySmallMessageNet(componentPlayer, "不可在主城投射物品！");
                return false;
            }
            return true;
        }

        /// <summary>
        /// Project的Load后执行
        /// </summary>
        public override void Load()
        {
            if (GameManager.Project != null)
            {
                SubsystemGameInfo = GameManager.Project.FindSubsystem<SubsystemGameInfo>();
            }
            try
            {
                MajorCityAreas.Clear();
                if (File.Exists(ConfigFilePath))
                {
                    using (StreamReader file = File.OpenText(ConfigFilePath))
                    {
                        string jsonText = file.ReadToEnd();
                        MajorCityAreas = JsonConvert.DeserializeObject<List<MajorCityArea>>(jsonText);
                    }
                }
                if (SubsystemGameInfo != null)
                {
                    foreach (var area in MajorCityAreas)
                    {
                        if (area.MinPoint.X > area.MaxPoint.X)
                        {
                            int temp = area.MaxPoint.X;
                            area.MaxPoint.X = area.MinPoint.X;
                            area.MinPoint.X = temp;
                        }
                        if (area.MinPoint.Y > area.MaxPoint.Y)
                        {
                            int temp = area.MaxPoint.Y;
                            area.MaxPoint.Y = area.MinPoint.Y;
                            area.MinPoint.Y = temp;
                        }
                        if (area.MinPoint.Z > area.MaxPoint.Z)
                        {
                            int temp = area.MaxPoint.Z;
                            area.MaxPoint.Z = area.MinPoint.Z;
                            area.MinPoint.Z = temp;
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Log.Error($"插件{Name}装载失败：{e.Message}");
            }
        }

        /// <summary>
        /// Project的Save后执行
        /// </summary>
        public override void Save()
        {
            //try
            //{
            //    string jsonText = JsonConvert.SerializeObject(MajorCityAreas);
            //    using (FileStream fileStream = File.Open(ConfigFilePath, FileMode.Create))
            //    {
            //        using (StreamWriter fileWrite = new StreamWriter(fileStream))
            //        {
            //            fileWrite.Write(jsonText);
            //            fileWrite.Flush();
            //        }
            //    }
            //}
            //catch (Exception e)
            //{
            //    Log.Error($"插件{Name}保存失败：{e.Message}");
            //}
        }

        /// <summary>
        /// 给指定玩家发送提示
        /// </summary>
        /// <param name="componentPlayer"></param>
        /// <param name="text"></param>
        public void DisplaySmallMessageNet(ComponentPlayer componentPlayer, string text)
        {
            var messagePackget = new MessagePackage(null, text, 0, null);
            messagePackget.To = componentPlayer.PlayerData.Client;
            CommonLib.Net.QueuePackage(messagePackget);
        }
    }
}